package websocket

import (
	"sync"
	"time"
)

type Server struct {
	Mutex   sync.RWMutex       // 读写锁
	Clients map[string]*Client // 所有的客户端
}

var WsServer = NewServer()

func NewServer() *Server {
	return &Server{
		Clients: make(map[string]*Client),
	}
}

// 添加客户端
func (s *Server) AddClients(key string, client *Client) {
	s.Mutex.Lock()
	defer s.Mutex.Unlock()

	client.Key = key
	s.Clients[key] = client
}

// 删除客户端
func (s *Server) DelClients(key string) (result bool) {
	s.Mutex.Lock()
	defer s.Mutex.Unlock()

	if _, ok := s.Clients[key]; ok {
		delete(s.Clients, key)
		result = true
	}
	return
}

// 定时清理超时连接
// 可以结合nginx处理长时间不活跃请求
func (s *Server) ClearTimeoutConnections() {
	currentTime := uint64(time.Now().Unix())

	for _, v := range s.Clients {
		// 如果超时15分钟
		if v.HeartbeatTime + 900 > currentTime {
			s.DelClients(v.Key)
			v.WsClose()
		}
	}
}